package com.xiaobai.dao;

import com.sun.istack.internal.Nullable;
import lombok.NonNull;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Objects;
import java.util.Properties;

/**
 * @Author 小白学CS
 * @Version 1.0
 */
/*操作数据库的公共类*/
public class BaseDao {
    /*获取链接*/
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    /*静态代码块，启动即加载，类加载的时候就初始化了*/
    static {
        //声明properties变量，读取properties文件
        Properties properties = new Properties();
        /*通过类加载器读取到对应的资源
         * 使用getResourceAsStream读取到db.properties*/
        InputStream resourceAsStream = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");


        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }

    /*获取数据库的连接*/
    public static Connection getConnection() {
        @Nullable Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    /*编写查询公共类*/
    public static ResultSet execute(Connection conn, PreparedStatement pstm, ResultSet rs, String sql,Object[] params) throws SQLException {
        //预编译的sql，在后面直接执行就可以了
        pstm = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            //setObject，占位符从1开始，但是数组是从0开始的
            pstm.setObject(i+1,params[i]);
        }
        rs= pstm.executeQuery(sql);
        return rs;
    }

    /*编写增删改工具方法类*/
    public static int execute(Connection conn, PreparedStatement pstm,ResultSet rs,  Objects[] params) throws SQLException {
        pstm = conn.prepareStatement(rs.toString());
        for (int i = 0; i < params.length; i++) {
            //setObject，占位符从1开始，但是数组是从0开始的
            pstm.setObject(i+1,params[i]);
        }
        int updataRows = pstm.executeUpdate(rs.toString());
        return updataRows;
    }
    /*关闭资源，释放资源*/
    public  static boolean closeResource(Connection conn, PreparedStatement pstm,  ResultSet rs) throws SQLException {
        boolean flag = true;
        if (rs != null) {
            rs.close();
            //GC垃圾回收
            rs = null;
        }
        if (pstm != null) {
            pstm.close();
            //GC垃圾回收
            pstm = null;
        }
        if (conn != null) {
            conn.close();
            //GC垃圾回收
            conn = null;
        }
        return flag;
    }
}